import 'dart:typed_data';

import 'package:ble_helper_plugin/library.dart';
import 'package:bluetooth_protocols_plugin/library.dart';
import 'package:flutter/material.dart';

import '../helper/encrypt_decryt_helper.dart';
import '../tools/utils.dart';

class LorinBluetoothInterceptor extends BluetoothInterceptor {
  @override
  List<int> requestInterception(List<int> data) {
    return data;
  }

  @override
  List<List<int>> responseInterception(List<int> data) {
    // 因为data是蓝牙发送与接收的原始数据，可能被加密过，所以需要【解密/去转义】后再解析
    // 加解密助手
    final EncryptDecryptHelper encryptDecryptHelper =
        EncryptDecryptHelper(LorinCrypto());
    Uint8List decryptData =
        encryptDecryptHelper.decrypt(Uint8List.fromList(data));
    int index = 0;
    List<List<int>> dataPacket = [];
    Uint8List bytes = Uint8List.fromList(decryptData);
    while (index < bytes.length) {
      try {
        LorinMessage msg = LorinMessage.fromList(bytes.sublist(index));
        dataPacket.add(encryptDecryptHelper.encrypt(msg.toBytes()));
        index += msg.totalLength();
      } catch (e) {
        debugPrint('数据包 (0x${Utils.uint8List2HexString(decryptData)}) 异常: $e');
        break;
      }
    }
    return dataPacket;
  }
}
